<template>
  <div class="home-page">
    <!-- 头部创作栏 -->
    <div class="home-top">
      <ai-creater />
      <!-- 轮播图 -->
      <carousel />
    </div>

    <!-- 搜索 -->
    <div class="bg-[#fff] px-[24px] py-[16px] sticky top-0 z-10">
      <!-- 产品标题区域 -->
      <div class="mt-[0px] flex justify-between items-start gap-[8px]">
        <div class="flex flex-wrap gap-2">
          <div
            class="flex items-center gap-[8px] cursor-pointer rounded-[6px] px-[16px] py-[8px] hover:bg-[#ededed] transition-all duration-200"
            :class="[
              activeTab === item.id
                ? 'bg-[#F76B1B] text-[#ffffff] hover:!bg-[#F76B1B]'
                : 'bg-[#F8F8F8] text-[#0A0A0A] ',
            ]"
            v-for="item in tabList"
            :key="item.id"
            @click="handleTabChange(item.id)">
            <IconRenderer
              v-if="item.icon"
              :name="item.icon"
              :color="activeTab === item.id ? '#ffffff' : '#0A0A0A'"
              :size="24" />
            <span class="text-[15px] font-[500]">{{ item.name }}</span>
          </div>
        </div>

        <div class="right flex items-center gap-[16px]">
          <div class="search-box">
            <div
              v-if="showSearch"
              class="search-el flex items-center gap-[8px] h-[40px] bg-[#F8F8F8] rounded-[52px] w-[530px] pl-[22px] pr-[2px]">
              <input
                v-model="search_text"
                @keyup.enter="goSearch"
                type="text"
                placeholder="What are you looking for?"
                class="w-full h-full outline-none text-[15px] font-[400] text-[#222222] placeholder-[#7A7A7A]" />

              <ClearIcon
                v-if="search_text"
                @click="search_text = ''"
                class="cursor-pointer flex-shrink-0" />

              <svg
                @click="goSearchBtn"
                class="cursor-pointer flex-shrink-0"
                width="32"
                height="32"
                viewBox="0 0 32 32"
                fill="none"
                xmlns="http://www.w3.org/2000/svg">
                <rect width="32" height="32" rx="16" fill="#F76B1B" />
                <path
                  d="M15.583 8.58301C19.4489 8.58301 22.5828 11.7172 22.583 15.583C22.583 17.3522 21.9252 18.9668 20.8428 20.1992L24.4473 23.8037C24.7397 24.0966 24.74 24.5715 24.4473 24.8643C24.1545 25.1568 23.6796 25.1566 23.3867 24.8643L19.7383 21.2158C18.576 22.0746 17.139 22.583 15.583 22.583C11.7172 22.5828 8.58301 19.4489 8.58301 15.583C8.58318 11.7173 11.7173 8.58318 15.583 8.58301ZM15.583 10.083C12.5457 10.0832 10.0832 12.5457 10.083 15.583C10.083 18.6205 12.5456 21.0828 15.583 21.083C18.6206 21.083 21.083 18.6206 21.083 15.583C21.0828 12.5456 18.6205 10.083 15.583 10.083Z"
                  fill="white" />
              </svg>
            </div>

            <svg
              v-else
              class="cursor-pointer flex-shrink-0"
              @click="handleSearchClick"
              width="24"
              height="24"
              viewBox="0 0 24 24"
              fill="none"
              xmlns="http://www.w3.org/2000/svg">
              <path
                d="M11.5 3.25C16.0563 3.25 19.75 6.94365 19.75 11.5C19.75 13.6356 18.9378 15.5809 17.6064 17.0459L22.0303 21.4697C22.3232 21.7626 22.3232 22.2374 22.0303 22.5303C21.7374 22.8232 21.2626 22.8232 20.9697 22.5303L16.5 18.0605C15.1125 19.1196 13.3802 19.75 11.5 19.75C6.94365 19.75 3.25 16.0563 3.25 11.5C3.25 6.94365 6.94365 3.25 11.5 3.25ZM11.5 4.75C7.77208 4.75 4.75 7.77208 4.75 11.5C4.75 15.2279 7.77208 18.25 11.5 18.25C15.2279 18.25 18.25 15.2279 18.25 11.5C18.25 7.77208 15.2279 4.75 11.5 4.75Z"
                fill="#494848" />
            </svg>
          </div>

          <el-popover placement="bottom" trigger="click" width="200px">
            <template #reference>
              <div
                class="flex items-center gap-[8px] px-[24px] py-[8px] text-[#0A0A0A] cursor-pointer text-[16px] rounded-[8px] bg-[#F8F8F8] hover:bg-[#ededed]">
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="24"
                  height="24"
                  viewBox="0 0 24 24"
                  fill="none">
                  <path
                    d="M2 4.5H22"
                    stroke="#222222"
                    stroke-linecap="round"
                    stroke-linejoin="round" />
                  <path
                    d="M5 9.5L19 9.5"
                    stroke="#222222"
                    stroke-linecap="round"
                    stroke-linejoin="round" />
                  <path
                    d="M7 14.5L17 14.5"
                    stroke="#222222"
                    stroke-linecap="round"
                    stroke-linejoin="round" />
                  <path
                    d="M9 19.5L15 19.5"
                    stroke="#222222"
                    stroke-linecap="round"
                    stroke-linejoin="round" />
                </svg>
                <span class="text-[16px] font-[500] text-[#0A0A0A]">Filter</span>
              </div>
            </template>
            <div class="p-[16px] gap-[16px] flex flex-col text-[16px] text-[#0A0A0A]">
              <div
                class="flex items-center justify-between cursor-pointer"
                @click="sortTypeChange('latest')">
                <span
                  :class="{ 'text-[#F76B1B]': sort_type === 'latest' }"
                  class="hover:font-[500]">
                  Latest
                </span>
                <el-icon color="#F76B1B" v-if="sort_type === 'latest'">
                  <Select />
                </el-icon>
              </div>
              <div
                class="flex items-center justify-between cursor-pointer"
                @click="sortTypeChange('likes')">
                <span :class="{ 'text-[#F76B1B]': sort_type === 'likes' }" class="hover:font-[500]">
                  Most Likes
                </span>
                <el-icon color="#F76B1B" v-if="sort_type === 'likes'"><Select /></el-icon>
              </div>
              <div
                class="flex items-center justify-between cursor-pointer"
                @click="sortTypeChange('comments')">
                <span
                  :class="{ 'text-[#F76B1B]': sort_type === 'comments' }"
                  class="hover:font-[500]">
                  Most Comments
                </span>
                <el-icon color="#F76B1B" v-if="sort_type === 'comments'">
                  <Select />
                </el-icon>
              </div>
            </div>
          </el-popover>
        </div>
      </div>
    </div>

    <Product
      id="productView"
      :products="products"
      :loading="loading"
      :loadMoreLoading="loadMoreLoading"
      :hasMore="userInfo ? hasMore : true" />

    <!-- 显示登录按钮 -->
    <div v-if="!userInfo" class="flex justify-center pb-[80px] pt-[30px]">
      <div
        v-hover-bg
        @click="onLoginDialogOpen"
        class="cursor-pointer bg-[#F76B1B] text-[#fff] px-[24px] py-[10px] rounded-[32px] font-[500]">
        Sign up to continue
      </div>
    </div>

    <FloatActions />

    <Overlay :visible="[1, 2].includes(newUserGuideStep || 0)">
      <div v-if="newUserGuideStep === 1" class="modal_guide pl-[200px] mt-[12px]">
        <img
          class="step1_img"
          src="https://imgs.nexbie.com/uploads/0668156ef5d3469d8e288b4bf1862fed.webp"
          alt="" />
        <div class="step_view">
          <UserGuideStep class="step1_view" />
        </div>
      </div>
      <div
        v-if="newUserGuideStep === 2"
        :style="{ marginTop: step2Height + 'px' }"
        class="pl-[200px] pr-[12px] step3_view relative">
        <UserGuideStep
          style="position: absolute; left: 50%; transform: translateX(-50%); top: -200px" />
        <img
          class="step3_img mt-[24px]"
          src="https://imgs.nexbie.com/uploads/9a4fed3010914ef583b0ee53f77389b2.webp"
          alt="" />
      </div>
    </Overlay>
  </div>
</template>

<script setup lang="ts">
  import Carousel from '@/views/home/components/carousel.vue';
  import Product from '@/views/home/components/product.vue';
  import IconRenderer from '@/components/icons/IconRenderer.vue';
  import Overlay from '@/components/Overlay.vue';
  import UserGuideStep from '@/components/UserGuideStep.vue';
  import { throttle } from 'lodash';
  import { Select } from '@element-plus/icons-vue';
  import {
    onMounted,
    ref,
    onUnmounted,
    computed,
    onActivated,
    onDeactivated,
    nextTick,
    watch,
  } from 'vue';
  import { FeedsAPI, type FeedItem, type FeedsParams } from '@/api/feeds';
  import request from '@/utils/request';
  import { useRetryEventBus } from '@/utils/retryEventBus';
  import { useRouter, useRoute, onBeforeRouteLeave } from 'vue-router';
  import { useUserStore } from '@/store/user';
  import { useLoginModal } from '@/composables/useLoginModal';
  import { bus, useBus } from '@/utils/bus';
  import AiCreater from '@/views/home/components/aiCreater.vue';
  import { getElementInfoById } from '@/utils/guideTools';
  import ClearIcon from '@/components/icons/home/ClearIcon.vue';

  const userStore = useUserStore();
  const router = useRouter();
  const route = useRoute();

  // 定义组件名称，用于keep-alive缓存
  defineOptions({
    name: 'HomePage',
  });

  const userInfo = computed(() => userStore.user);
  const isLoggedIn = computed(() => userStore.isAuthenticated);
  const newUserGuideStep = computed(() => userStore.newUserGuideStep);
  // Tab相关数据
  const activeTab = ref(1);
  // 分页相关数据
  const start = ref(0);
  const loading = ref(false);
  // 产品数据
  const products = ref<FeedItem[]>([]);
  const sort_type = ref<'latest' | 'likes' | 'comments'>('latest');
  const search_text = ref('');

  const searchLoading = ref(false);
  const searchTimeout = ref<number | any>(null);

  // 触底加载相关
  const loadMoreLoading = ref(false);
  const hasMore = ref(true);
  const scrollTimeout = ref<number | any>(null);

  // 缓存控制
  const isDataLoaded = ref(false);
  const isActivated = ref(false);
  const isFirstMount = ref(true);
  const isReturningFromOtherPage = ref(false);
  const savedScrollPosition = ref(0);
  // 处理页面加载数据中就点击进入作品详情，瀑布流获取不到页面高度，在作品详情页返回图片堆叠到一起
  const isLeavePageLoadingMore = ref<boolean>(false);
  const isInHomePage = ref<boolean>(true); // 当前处于Home page页
  // 发布作品相关
  const publishedFeedId = ref<string | null>(null);

  const showSearch = ref<boolean>(false);
  const productRef = ref(null);
  const step2Height = ref(0);

  const getDistance = () => {
    const el: any = getElementInfoById('productView');
    step2Height.value = el.top;
  };

  const handleSearchClick = () => {
    showSearch.value = !showSearch.value;
  };

  const goSearchBtn = () => {
    if (search_text.value.trim() === '') {
      handleSearchClick();
      return;
    }
    goSearch();
  };

  const goSearch = () => {
    router.push({
      path: '/search',
      query: {
        q: search_text.value,
      },
    });
  };

  // Tab列表数据
  const tabList = ref([
    {
      id: 1,
      name: 'For you',
      icon: 'star',
      component: 'ForYou',
    },
    {
      id: 2,
      name: 'Following',
      icon: 'trending',
      component: 'Trending',
    },
    {
      id: 3,
      name: 'Contest',
      icon: 'new',
      component: 'New',
    },
    // {
    //   id: 4,
    //   name: 'Popular',

    //   component: 'Popular',
    // },
    // {
    //   id: 5,
    //   name: 'Design',
    //   component: 'Design',
    // },
    // {
    //   id: 6,
    //   name: 'Art',
    //   component: 'Art',
    // },
    // {
    //   id: 7,
    //   name: 'Photography',
    //   component: 'Photography',
    // },
    // {
    //   id: 8,
    //   name: 'Fashion',
    //   component: 'Fashion',
    // },
  ]);

  // 更新评论数量
  const refreshCommentNum = (data: any) => {
    products.value.forEach((item: FeedItem) => {
      if (item?.feed_id === data.feed_id) {
        item.counter.comment_count = data.total_comment;
      }
    });
  };

  // 更新点赞、点赞数量
  const refreshLike = (data: any) => {
    products.value.forEach((item: FeedItem) => {
      if (item?.feed_id === data?.feed_id) {
        item.counter.like_count = data?.like_count;
        item.like_flag = data?.like_flag;
      }
    });
  };

  // Tab切换处理
  const handleTabChange = (tabId: number) => {
    console.log('Tab切换:', tabId);
    activeTab.value = tabId;
    start.value = 0; // 切换tab时重置到第一页
    products.value = [];
    // 清除缓存，强制刷新
    isDataLoaded.value = false;
    loadProducts(false, true);
  };

  const sortTypeChange = (type: 'latest' | 'likes' | 'comments') => {
    sort_type.value = type;
    start.value = 0; // 切换tab时重置到第一页
    products.value = [];
    // 清除缓存，强制刷新
    isDataLoaded.value = false;
    loadProducts(false, true);
  };

  // 全局悬浮操作 - 登录按钮点击
  const onLoginClick = () => {
    router.push('/login');
  };

  // 打开登录弹窗
  const onLoginDialogOpen = () => {
    const { showModal } = useLoginModal();
    showModal();
  };

  // 检查是否已加载数据
  const hasData = () => {
    return isDataLoaded.value && products.value.length > 0;
  };

  // 保存滚动位置
  const saveScrollPosition = () => {
    // 使用nextTick确保DOM更新完成后再保存
    nextTick(() => {
      savedScrollPosition.value = window.pageYOffset || document.documentElement.scrollTop;
    });
  };

  // 恢复滚动位置（无动画）
  const restoreScrollPosition = () => {
    if (savedScrollPosition.value > 0) {
      // 使用nextTick确保DOM渲染完成后再恢复
      nextTick(() => {
        // 使用scrollTo的behavior: 'instant'来避免滚动动画
        window.scrollTo({
          top: savedScrollPosition.value,
          left: 0,
          behavior: 'instant',
        });
        console.log('恢复滚动位置:', savedScrollPosition.value);
      });
    }
  };

  // 获取产品数据
  const loadProducts = async (isLoadMore = false, forceRefresh = false) => {
    // 如果是加载更多，直接执行
    if (isLoadMore) {
      await fetchProducts(isLoadMore);
      return;
    }

    // 检查是否已有数据且不需要强制刷新
    if (!forceRefresh && hasData()) {
      console.log('使用缓存数据，跳过接口调用');
      return;
    }

    await fetchProducts(isLoadMore);
  };

  // 实际的数据获取函数
  const fetchProducts = async (isLoadMore = false) => {
    try {
      if (isLoadMore) {
        loadMoreLoading.value = true;
      } else {
        loading.value = true;
      }

      // 如果有发布的作品ID，先获取该作品数据
      if (!isLoadMore && publishedFeedId.value) {
        console.log('检测到发布作品ID，优先获取该作品数据:', publishedFeedId.value);
        await fetchPublishedFeed();
        // 清除已处理的feed_id
        publishedFeedId.value = null;
      }

      const params: FeedsParams = {
        start: start.value,
        size: 30,
        category_id: activeTab.value,
        sort_type: sort_type.value,
        search_text: search_text.value.trim() || undefined,
      };

      // 根据是否登录选择不同的API
      let apiUrl = isLoggedIn.value ? '/feeds/feature' : '/feeds/homepage';

      const response = await request.post(apiUrl, params);

      // 处理页面加载数据中就点击进入作品详情，瀑布流获取不到页面高度，在作品详情页返回图片堆叠到一起
      if (isLeavePageLoadingMore.value) {
        loading.value = false;
        searchLoading.value = false;
        loadMoreLoading.value = false;
        return;
      }

      if (response.code == 200 && response.data.feeds && response.data.feeds.length > 0) {
        products.value = [...products.value, ...response.data.feeds];
      }

      // if (isLoadMore) {
      //   // 追加数据
      //   products.value = [...products.value, ...response.data.feeds];
      // } else {
      //   // 替换数据
      //   products.value = response.data.feeds;
      // }

      start.value = response.data.next_start;

      // 检查是否还有更多数据
      // 未登录用户禁用分页
      if (!isLoggedIn.value || !userInfo.value) {
        hasMore.value = false; // 未登录用户禁用分页
        console.log('未登录用户，禁用分页功能');
      } else {
        hasMore.value = response.data.has_more;
      }

      // 更新数据加载状态
      isDataLoaded.value = true;

      console.log('加载产品数据成功:', response);
    } catch (error) {
      console.error('加载产品数据失败:', error);
    } finally {
      loading.value = false;
      searchLoading.value = false;
      loadMoreLoading.value = false;
    }
  };

  // 触底加载更多数据
  const loadMore = async () => {
    if (loadMoreLoading.value || !hasMore.value || loading.value) return;
    // 只有登录用户才能触底加载更多
    if (!isLoggedIn.value || !userInfo.value) {
      console.log('未登录用户，禁用触底加载');
      return;
    }

    // 更新start值以获取下一页数据
    start.value = products.value.length;

    await loadProducts(true);
  };

  watch(
    // 监听全局当前路由的响应式对象
    () => router.currentRoute.value,
    (newRoute) => {
      isInHomePage.value = newRoute.path === '/';
    },
    { immediate: true } // 初始化时立即执行一次，获取当前路由
  );

  // 监听用户登录状态变化
  watch(isLoggedIn, (newValue, oldValue) => {
    console.log('用户登录状态变化:', { newValue, oldValue });
    // 当登录状态发生变化时，重置数据并重新加载 isInHomePage 处于当前页才刷新，不然会导致瀑布流塌陷
    if (newValue !== oldValue && isInHomePage.value) {
      console.log('登录状态变化，重新加载数据');
      start.value = 0;
      products.value = [];
      isDataLoaded.value = false;
      loadProducts(false, true);
    }
  });

  // 监听路由参数变化，获取feed_id
  watch(
    () => route.query.feed_id,
    (newFeedId) => {
      console.log('检测到feed_id参数变化:', newFeedId);
      if (newFeedId && typeof newFeedId === 'string') {
        publishedFeedId.value = newFeedId;
        console.log('设置发布作品ID:', newFeedId);
        // 只在首页清除URL参数，避免刷新页面时重复处理
        if (route.name === 'HomePage') {
        }
      }
    },
    { immediate: true }
  );

  // 滚动监听函数（节流处理）
  const handleScroll = () => {
    // 如果组件刚激活，延迟处理滚动事件
    if (!isActivated.value) {
      return;
    }
    // 如果是从其他页面返回，禁用滚动加载
    if (isReturningFromOtherPage.value) {
      console.log('从其他页面返回，禁用滚动加载');
      return;
    }
    // 未登录用户禁用触底加载
    if (!isLoggedIn.value || !userInfo.value) {
      console.log('未登录用户，禁用滚动触底加载');
      return;
    }
    // 如果正在加载或没有更多数据，则不处理滚动
    if (loadMoreLoading.value || !hasMore.value) {
      return;
    }
    const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    const windowHeight = window.innerHeight;
    const documentHeight = document.documentElement.scrollHeight;
    // 当滚动到距离底部300px时触发加载
    if (scrollTop + windowHeight >= documentHeight - 300) {
      loadMore();
    }
  };

  const throttleHandleScroll: any = throttle(handleScroll, 300);

  // 重试事件处理
  // const { on } = useRetryEventBus();

  // // 监听重试成功事件
  // on('request_retry_success', (event: any) => {
  //   console.log('收到重试成功事件:', event);

  //   // 检查是否是feeds相关的请求
  //   if (event.url && event.url.includes('/feeds/feature')) {
  //     console.log('检测到feeds请求重试成功，重新加载数据');
  //     products.value = [];
  //     // 重新调用loadProducts来更新数据
  //     loadProducts();
  //   }
  // });

  // 路由离开前保存滚动位置
  onBeforeRouteLeave((to: any, from: any, next: any) => {
    console.log('路由离开前保存滚动位置');
    // 数据加载更多时候就离开页面
    if (loadMoreLoading.value) {
      isLeavePageLoadingMore.value = true;
    }
    saveScrollPosition();
    next();
  });

  // 获取发布的作品数据并放在瀑布流第一位
  const fetchPublishedFeed = async () => {
    if (!publishedFeedId.value) return;

    try {
      const response = await FeedsAPI.getFeed({
        feed_id: publishedFeedId.value,
      });

      if (response.code === 200 && response.data) {
        const publishedFeed = response.data;
        console.log('成功获取发布作品===:', publishedFeed);

        // 将发布的作品放在瀑布流第一位
        products.value = [publishedFeed, ...products.value];
      } else {
        console.warn('获取发布作品失败或数据为空:', response);
      }
    } catch (error) {
      console.error('获取发布作品数据失败:', error);
    }
  };

  // 处理如果是发布流程过来，则需要在第一个显示她的作品
  // 支持动态feed_id参数
  const handleAddFeed = async (feedId?: string) => {
    const targetFeedId = feedId || publishedFeedId.value || '7387017478238416896';

    if (!targetFeedId) {
      console.warn('没有提供feed_id参数');
      return;
    }

    try {
      console.log('handleAddFeed - 获取作品数据:', targetFeedId);
      const response = await FeedsAPI.getFeed({
        feed_id: targetFeedId,
      });

      if (response.code === 200 && response.data.feeds && response.data.feeds.length > 0) {
        const feedData = response.data.feeds[0];
        console.log('handleAddFeed - 成功获取作品:', feedData);

        // 将作品放在瀑布流第一位
        products.value = [feedData, ...products.value];
        console.log('handleAddFeed - 作品已添加到瀑布流第一位');
      } else {
        console.warn('handleAddFeed - 获取作品失败或数据为空:', response);
      }
    } catch (error) {
      console.error('handleAddFeed - 获取作品数据失败:', error);
    }
  };

  // 组件挂载时加载数据
  onMounted(() => {
    console.log('组件挂载');

    // 设置激活状态
    isActivated.value = true;
    // 首次加载数据
    loadProducts();
    // 标记首次挂载完成

    nextTick(getDistance);

    window.addEventListener('scroll', throttleHandleScroll);
    bus.on('detail:comment', refreshCommentNum);
    bus.on('detail:isLike', refreshLike);
  });

  // 组件被激活时（从缓存中恢复）
  onActivated(() => {
    console.log('首页组件被激活');
    // 如果是首次挂载，跳过处理（onMounted已经处理了）
    if (isFirstMount.value) {
      isFirstMount.value = false;
      console.log('首次挂载，跳过onActivated处理');
      return;
    }

    // 重新添加滚动监听
    window.addEventListener('scroll', throttleHandleScroll);

    // 延迟恢复滚动位置，确保DOM完全渲染
    setTimeout(() => {
      restoreScrollPosition();
    }, 100); // 100ms延迟

    // 延迟激活滚动处理，避免立即触发
    setTimeout(() => {
      isActivated.value = true;
    }, 500); // 500ms延迟

    // 延迟重置返回标志，允许正常滚动加载
    setTimeout(() => {
      isReturningFromOtherPage.value = false;
      console.log('重置返回标志，允许正常滚动加载');
    }, 1000); // 1秒后允许正常滚动加载

    // 检查是否有新的feed_id参数需要处理
    const currentFeedId = route.query.feed_id as string;
    if (currentFeedId && currentFeedId !== publishedFeedId.value) {
      console.log('检测到新的feed_id参数，重新加载数据:', currentFeedId);
      publishedFeedId.value = currentFeedId;
      // 清除URL参数
      router.replace({ query: {} });
      // 重新加载数据
      start.value = 0;
      products.value = [];
      isDataLoaded.value = false;
      loadProducts(false, true);
    } else if (isLeavePageLoadingMore.value) {
      loadMore();
      console.log('加载更多情况');
    } else if (hasData()) {
      console.log('使用缓存数据，跳过接口调用');
    } else {
      console.log('无缓存数据，重新加载');
      loadProducts();
    }
    isLeavePageLoadingMore.value = false;
    showSearch.value = false;
    search_text.value = '';
  });

  // 组件被停用时（离开页面）
  onDeactivated(() => {
    console.log('首页组件被停用，离开页面');

    // 标记为从其他页面返回
    isReturningFromOtherPage.value = true;
    console.log('设置返回标志，下次激活时将禁用滚动加载');

    // 移除滚动监听
    window.removeEventListener('scroll', throttleHandleScroll);
  });

  // 组件卸载时清理事件监听
  onUnmounted(() => {
    window.removeEventListener('scroll', throttleHandleScroll);
    if (searchTimeout.value) {
      clearTimeout(searchTimeout.value);
    }
    bus.off('detail:comment', refreshCommentNum);
    bus.off('detail:isLike', refreshLike);
  });
</script>

<style scoped lang="scss">
  .home-page {
    width: 100%;
    min-height: 100vh;

    background: white;
  }

  .home-top {
    display: flex;
    gap: 24px;
    padding: 24px;
    padding-bottom: 16px;
    min-height: 200px;
  }

  .top-container {
    display: flex;
    align-items: center;
    gap: 16px;
    width: 100%;
  }

  .search-input-wrapper {
    position: relative;
    width: 100%;
  }

  .search-icon {
    position: absolute;
    left: 16px;
    top: 50%;
    transform: translateY(-50%);
    width: 20px;
    height: 20px;
    color: #9ca3af;
    z-index: 1;
    pointer-events: none;
  }
  .search-el {
    transition: all 0.3s ease;
    border: 2px solid transparent;
    outline: none;
    input {
      background: transparent;
    }
    &:focus-within,
    &:hover {
      border: 2px solid #fbe6db;
      background: transparent;
    }
  }
  .search-input {
    width: 100%;
    height: 48px;
    padding: 12px 16px 12px 48px;
    border: 2px solid #ededed;
    border-radius: 8px;
    font-size: 16px;
    background: #ededed;
    transition: all 0.3s ease;
    outline: none;

    &:focus {
      box-shadow: 0 0 0 3px rgba(245, 245, 245, 1);
    }

    &::placeholder {
      color: #7a7a7a;
    }
  }

  .clear-search-btn {
    position: absolute;
    right: 12px;
    top: 50%;
    transform: translateY(-50%);
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #9ca3af;
    color: white;
    border: none;
    border-radius: 50%;
    cursor: pointer;
    transition: all 0.2s ease;
    z-index: 2;

    &:hover {
      background: #6b7280;
      transform: translateY(-50%) scale(1.1);
    }
  }

  .search-loading {
    position: absolute;
    right: 12px;
    top: 50%;
    transform: translateY(-50%);
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #9ca3af;
    z-index: 2;
  }

  .get-started-btn {
    padding: 12px 24px;
    color: #222;
    border-radius: 12px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
    white-space: nowrap;
    font-size: 15px;
    &:hover {
      color: #7a7a7a;
    }
  }
  .show_search_tips {
    margin-left: 24px;
    color: var(---9, #222);
    font-family: 'Inter Tight';
    font-size: 20px;
    font-style: normal;
    font-weight: 500;
    line-height: normal;
    .search_text_color {
      color: #7a7a7a;
    }
  }
  .modal_guide {
    display: flex;
    flex-direction: row;
    .step1_img {
      flex: 1;
      max-width: 744px;
      max-height: 344px;
      min-width: 0;
    }
    .step1_view {
      margin-left: 24px;
    }
    .step3_img {
      width: 100%;
      height: auto;
    }
    .step_view {
      display: flex;
      flex-direction: column-reverse;
      flex-shrink: 0;
    }
    .step3_view {
      display: flex;
      flex-direction: column;
    }
  }
</style>
